package cn.edu.csmzxy.rk233x.auth_system.service.impl;

import cn.edu.csmzxy.rk233x.auth_system.entity.SysPermission;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysPermissionMapper;
import cn.edu.csmzxy.rk233x.auth_system.service.SysPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.edu.csmzxy.rk233x.auth_system.dto.PermissionDTO;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysRolePermission;
import cn.edu.csmzxy.rk233x.auth_system.exception.BusinessException;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysRolePermissionMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wumxing
 * @date 2025/10/15 9:51
 * @description  权限管理服务实现
 */

@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;

    @Override
    public List<SysPermission> selectPermissionTree() {
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPermission::getIsDeleted, 0)
                .orderByAsc(SysPermission::getSort);
        List<SysPermission> allPermissions = permissionMapper.selectList(wrapper);
        return buildPermissionTree(allPermissions, 0L);
    }

    private List<SysPermission> buildPermissionTree(List<SysPermission> allPermissions, Long parentId) {
        List<SysPermission> children = allPermissions.stream()
                .filter(permission -> permission.getParentId().equals(parentId))
                .collect(Collectors.toList());

        for (SysPermission child : children) {
            child.setChildren(buildPermissionTree(allPermissions, child.getId()));
        }
        return children;
    }

    @Override
    public List<Long> selectPermissionIdsByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRolePermission::getRoleId, roleId);
        return rolePermissionMapper.selectList(wrapper).stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void addPermission(PermissionDTO permissionDTO) {
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPermission::getCode, permissionDTO.getCode())
                .eq(SysPermission::getIsDeleted, 0);
        if (permissionMapper.exists(wrapper)) {
            throw new BusinessException("权限编码已存在");
        }

        SysPermission permission = new SysPermission();
        BeanUtils.copyProperties(permissionDTO, permission);
        permissionMapper.insert(permission);
    }

    @Override
    @Transactional
    public void updatePermission(Long id, PermissionDTO permissionDTO) {
        SysPermission permission = permissionMapper.selectById(id);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }

        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPermission::getCode, permissionDTO.getCode())
                .ne(SysPermission::getId, id)
                .eq(SysPermission::getIsDeleted, 0);
        if (permissionMapper.exists(wrapper)) {
            throw new BusinessException("权限编码已存在");
        }

        BeanUtils.copyProperties(permissionDTO, permission);
        permission.setId(id);
        permissionMapper.updateById(permission);
    }

    @Override
    @Transactional
    public void deletePermission(Long id) {
        // 检查是否有子权限
        LambdaQueryWrapper<SysPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPermission::getParentId, id)
                .eq(SysPermission::getIsDeleted, 0);
        if (permissionMapper.exists(wrapper)) {
            throw new BusinessException("请先删除子权限");
        }

        // 检查是否有关联角色
        LambdaQueryWrapper<SysRolePermission> rpWrapper = new LambdaQueryWrapper<>();
        rpWrapper.eq(SysRolePermission::getPermissionId, id);
        if (rolePermissionMapper.exists(rpWrapper)) {
            throw new BusinessException("该权限已关联角色，不能删除");
        }

        permissionMapper.deleteById(id);
    }
}
